package com.deductive.common.config.mybatis;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.Geometry;

import java.io.IOException;
import java.io.StringReader;

/**
 * Jackson deserializer to convert GeoJSON to JTS Geometry objects
 */
public class GeoJsonToGeometryDeserializer extends JsonDeserializer<Geometry> {

    @Override
    public Geometry deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        if (node == null || node.isNull()) {
            return null;
        }

        try {
            // Use GeoTools to parse the GeoJSON string into a JTS Geometry object
            GeometryJSON gjson = new GeometryJSON();
            return gjson.read(new StringReader(node.toString()));
        } catch (Exception e) {
            throw new IOException("Error deserializing GeoJSON to Geometry", e);
        }
    }
}
